import 'dart:ffi';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/pages/home/home/model/device_list_resp.dart';
import 'package:tracker/pages/home/home/model/home_device_info_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/enums/user_type_enum.dart';
import '../../../login/model/login_resp.dart';

/// 切换设备 页面
class DeviceListPage extends ConsumerStatefulWidget {
  const DeviceListPage({super.key});

  @override
  ConsumerState<DeviceListPage> createState() => _DeviceListPageState();
}

class _DeviceListPageState extends ConsumerState<DeviceListPage> {
  String _searchKeyword = ''; // 搜索关键词
  List<DeviceListData> _filteredData = <DeviceListData>[]; // 过滤后的数据

  bool showLoading = true;
  int pageNum = 1;
  List<DeviceListData> deviceList = <DeviceListData>[];
  late EasyRefreshController _refreshController;

  _buildLoading() {
    return Center(
      child: CircularProgressIndicator(
        color: AppTheme.themeConfig.primaryColor,
      ),
    );
  }

  _buildList() {
    return ListView.builder(
      itemCount: deviceList.length,
      itemBuilder: (context, index) {
        return _buildCell(index);
      },
    );
  }

  _buildCell(int index) {
    DeviceInfoVO deviceInfo = ref.watch(deviceInfoProvider);
    DeviceListData device = deviceList[index];
    bool isCurrentDevice = deviceInfo.imei == device.imei;
    // 设备信息cell
    return GestureDetector(
      onTap: () async {
        // 跳转到设备信息页面
        if (isCurrentDevice) {
          context.pop();
        } else {
          ref.read(deviceInfoProvider.notifier).switchImei(device.imei!, () {
            context.pop();
          });
        }
      },
      child: Stack(
        children: [
          Container(
            height: 60,
            margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
            padding: const EdgeInsets.only(
              left: 20,
              right: 20,
            ),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      // 设备名称和设备码
                      Text(
                        '${device.deviceName}',
                        style: TextStyle(
                          fontSize: 16,
                          color: AppTheme.themeConfig.primaryTextColor,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      const SizedBox(
                        width: 10,
                      ),
                      Text(
                        '设备号：${device.imei ?? ''}',
                        style: TextStyle(
                          fontSize: 14,
                          color: AppTheme.themeConfig.secondaryTextColor,
                        ),
                      ),
                    ],
                  ),
                ),
                // 设备状态
                _buildDeviceStatus(device.deviceStatus ?? 0),
              ],
            ),
          ),
          // 右上角显示当前设备标签
          if (isCurrentDevice)
            Positioned(
              top: 20,
              right: 20,
              child: Container(
                // height: 20,
                alignment: Alignment.center,
                padding: const EdgeInsets.only(
                  left: 4,
                  right: 4,
                ),
                decoration: BoxDecoration(
                    color: AppTheme.themeConfig.primaryColor,
                    borderRadius: BorderRadius.only(
                      topRight: Radius.circular(8),
                      bottomLeft: Radius.circular(8),
                    )),
                child: const Icon(Icons.check, color: Colors.white, size: 16),
              ),
            )
        ],
      ),
    );
  }

  Widget _buildDeviceStatus(int deviceStatus) {
    switch (deviceStatus) {
      case 2:
        return _buildDeviceStatusView('离线', '#909399');
      case 1:
        return _buildDeviceStatusView('在线', '#19be6b');
      case 3:
        return _buildDeviceStatusView('睡眠', '#ff9900');
      case 4:
        return _buildDeviceStatusView('关机', '#fa3534');
      default:
        return _buildDeviceStatusView('未激活', '#c8c9cc');
    }
  }

  Widget _buildDeviceStatusView(String text, String color) {
    return Container(
      margin: const EdgeInsets.only(left: 10),
      padding: const EdgeInsets.only(left: 10, right: 10, top: 2, bottom: 2),
      decoration: BoxDecoration(
        color: ColorUtils.hexToColor(color),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Text(
        text,
        style: const TextStyle(
          color: Colors.white,
          fontSize: 12,
        ),
      ),
    );
  }

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // 在build完成后回调
      // 获取设备列表
      _searchDeviceList(true);
    });
    super.initState();
    _refreshController = EasyRefreshController(
      controlFinishLoad: true,
      controlFinishRefresh: true,
    );
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchDeviceList(bool isRefresh) async {
    final queryParams = {
      'pageNum': pageNum,
      'pageSize': 10,
    };
    final res = await get<DeviceListResp, DeviceListResp>('/device/list',
        queryParameters: queryParams, decodeType: DeviceListResp());
    res.when(success: (DeviceListResp resp) {
      if (resp.code == 200) {
        if (isRefresh) {
          deviceList.clear();
          deviceList.addAll(resp.data!);
          // 判断是否还有更多数据
          if (resp.data == null || resp.data!.isEmpty || resp.data!.length < 10) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            _refreshController.finishRefresh();
          }
          pageNum++;
        } else {
          if (resp.data == null || resp.data!.isEmpty) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            pageNum++;
            deviceList.addAll(resp.data!);
            _refreshController.finishLoad();
          }
        }
      } else {
        ToastUtils.showToast(resp.msg ?? '获取设备列表失败');
      }
      setState(() {
        showLoading = false;
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备列表失败 code: $code msg: $msg');
    });
  }

  // JSON数据过滤逻辑
  _searchDeviceList(bool isRefresh) async {
    final userType = ref.watch(userTypeProvider);
    LoginData loginData = SpUtil.getObj('loginData', (v) => LoginData().fromJson(v));

    XLogger.debug(userType);
    XLogger.debug(UserTypeEnum.agent);

    XLogger.debug(userType == (UserTypeEnum.agent));
    final queryParams = {
      'pageNum': pageNum,
      'pageSize': 10,
      if (_searchKeyword.isNotEmpty) 'imei': _searchKeyword,
      if (userType == (UserTypeEnum.phone)) 'phone': loginData.phone,
      if (userType == (UserTypeEnum.agent)) 'userId': loginData.userId,
    };

    final res = await get<DeviceListResp, DeviceListResp>('$newBaseULr/device/list',
        queryParameters: queryParams, decodeType: DeviceListResp());
    res.when(success: (DeviceListResp resp) {
      if (resp.code == 200) {
        if (isRefresh) {
          deviceList.clear();
          deviceList.addAll(resp.data!);
          // 判断是否还有更多数据
          if (resp.data == null || resp.data!.isEmpty || resp.data!.length < 10) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            _refreshController.finishRefresh();
          }
          pageNum++;
        } else {
          if (resp.data == null || resp.data!.isEmpty) {
            _refreshController.finishLoad(IndicatorResult.noMore);
          } else {
            pageNum++;
            deviceList.addAll(resp.data!);
            _refreshController.finishLoad();
          }
        }
      } else {
        ToastUtils.showToast(resp.msg ?? '获取设备列表失败');
      }
      setState(() {
        showLoading = false;
      });
    }, failure: (String msg, int code) {
      XLogger.error('获取设备列表失败 code: $code msg: $msg');
    });
  }

// 自定义搜索框组件
  Widget _buildSearchBar() {
    return TextField(
      decoration: InputDecoration(
        hintText: '搜索设备名称/编号',
        hintStyle: TextStyle(color: Colors.white70),
        border: InputBorder.none,
        suffixIcon: Icon(Icons.search, color: Colors.white),
      ),
      style: TextStyle(color: Colors.white),
      cursorColor: Colors.white,
      onChanged: (value) {
        setState(() {
          pageNum = 1;
          _searchKeyword = value;
          _searchDeviceList(true);
        });
      },
    );
  }
  @override
  Widget build(BuildContext context) {
    final userType = ref.watch(userTypeProvider);
    bool showSearch = false;
    if (userType == UserTypeEnum.phone || userType == UserTypeEnum.agent) {
      showSearch = true;
    }
    return Scaffold(
      appBar: AppBar(
        title: showSearch ? _buildSearchBar() : Text('切换设备',style: TextStyle(
          color: Colors.white, // 明确指定文本颜色
          fontSize: 18, // 明确指定字体大小
        ),),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        foregroundColor: Colors.white,
      ),
      backgroundColor: ColorUtils.hexToColor('#f5f5f5'),
      body: EasyRefresh(
        controller: _refreshController,
        onRefresh: () async {
          pageNum = 1;
          await _searchDeviceList(true);
          _refreshController.finishRefresh();
        },
        onLoad: () async {
          await _searchDeviceList(false);
        },
        child: showLoading ? _buildLoading() : _buildList(),
      ),
    );
  }
}
